import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Scheduler extends Setup {
	static public int K = 10;
	static String HOME = "../";
	static String BLOCK_PATH = HOME + "predictions/AUM/val/" + K + "/";
	static int BEGIN = 0;
	static int END = 1000990;

	public static void main(String[] args) {
		makeFolder();
		setUserBPath();
		writeLastRunSettings();
		setup();
		execute();
	}

	static void makeFolder() {
		File folder = new File(BLOCK_PATH);
		if (!folder.exists()) {
			folder.mkdirs();
		}
	}

	static void writeLastRunSettings() {
		File file = new File(HOME + "lastRunSettings.txt");
		FileWriter fw;
		try {
			fw = new FileWriter(file);
			fw.write(BLOCK_PATH);
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void setUserBPath() {
		if (BLOCK_PATH.contains("val")) {
			Setup.FILE_PATH_USER_B = "../track1/validationIdx1.txt" + ".ser";
		} else {
			Setup.FILE_PATH_USER_B = "../track1/testIdx1.txt" + ".ser";
		}
	}

	static void execute() {
		int availableProcessors = Runtime.getRuntime().availableProcessors();
		ExecutorService es = Executors.newFixedThreadPool(availableProcessors);
		for (int start = BEGIN; start < END; start += K) {
			int stop = start + K;
			if (stop > END) {
				stop = END;
			}
			es.execute(alg(start, stop));
		}
		es.shutdown();
	}

	static Runnable alg(int start, int stop) {
		/* Algorithm User Mean */
		if (BLOCK_PATH.contains("AUM"))
			return new AUM(start, stop);
		/* Algorithm Item Mean */
		else if (BLOCK_PATH.contains("AIM"))
			return new AIM(start, stop);
		/* Algorithm User Similarity */
		else if (BLOCK_PATH.contains("AUS"))
			return new AUS(start, stop);
		/* Algorithm Item Similarity */
		else if (BLOCK_PATH.contains("AIS"))
			return new AIS(start, stop);
		/* You forgot to add your Algorithm ERROR! */
		else
			System.out.println("Forgot to add your Algorithm! " + BLOCK_PATH);
		return null;
	}

	void writeBlock(byte[] BLOCK, int start) {
		File out = new File(BLOCK_PATH + start + ".bin");
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(out);
			fos.write(BLOCK);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}